package com.forever.okhttpdemo.http;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClient {

	public static byte[] loadByteFromGet(String geturl) {

		try {
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(geturl);
			// 执行
			HttpResponse response = client.execute(get);

			if (response.getStatusLine().getStatusCode() == 200) {

				HttpEntity entity = response.getEntity();

				return EntityUtils.toByteArray(entity);

			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	public static byte[] loadByteFromPost(String geturl, String username,
			String password) {

		try {
			DefaultHttpClient client = new DefaultHttpClient();

			HttpPost post = new HttpPost(geturl);
			NameValuePair pair1 = new BasicNameValuePair("username", username);
			NameValuePair pair2 = new BasicNameValuePair("password", password);
			// 不懂，反正是固定格式。传送账号，密码。
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			list.add(pair1);
			list.add(pair2);

			HttpEntity Sendentity = new UrlEncodedFormEntity(list);

			post.setEntity(Sendentity);

			HttpResponse response = client.execute(post);

			if (response.getStatusLine().getStatusCode() == 200) {

				HttpEntity Backentity = response.getEntity();

				return EntityUtils.toByteArray(Backentity);

			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

}
